package com.chookss.video.recommend;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.aliyun.player.IPlayer;
import com.aliyun.player.alivcplayerexpand.listener.OnAutoPlayListener;
import com.aliyun.player.alivcplayerexpand.theme.Theme;
import com.aliyun.player.alivcplayerexpand.util.Common;
import com.aliyun.player.alivcplayerexpand.util.database.DatabaseManager;
import com.aliyun.player.alivcplayerexpand.util.tipsview.ErrorInfo;
import com.aliyun.player.alivcplayerexpand.view.choice.AlivcShowMoreDialog;
import com.aliyun.player.alivcplayerexpand.view.control.ControlView;
import com.aliyun.player.alivcplayerexpand.view.gesturedialog.BrightnessDialog;
import com.aliyun.player.alivcplayerexpand.view.more.AliyunShowMoreValue;
import com.aliyun.player.alivcplayerexpand.view.more.ShowMoreView;
import com.aliyun.player.alivcplayerexpand.view.more.SpeedValue;
import com.aliyun.player.alivcplayerexpand.widget.AliyunVodPlayerView;
import com.aliyun.player.source.VidAuth;
import com.aliyun.svideo.base.utils.AliyunScreenMode;
import com.aliyun.svideo.common.utils.ScreenUtils;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.studyPlan.StudyPlanAddActivity;
import com.chookss.mine.MyOrderPagerAdapter;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.VideoEvent;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.entity.VideoDetailEntity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.CircleImageView;
import com.chookss.view.DrawableTextView;
import com.chookss.view.ForScreenInitDialog;
import com.chookss.view.ProgressBarView;
import com.chookss.view.SelectDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.chookss.view.consecutivescroller.ConsecutiveViewPager;
import com.chookss.view.consecutivescroller.TabPagerAdapter;
import com.chookss.wxapi.ShareActivity;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * 播放器和播放列表界面 Created by Mulberry on 2018/4/9.
 */
public class VedioDetailActivity extends BaseAct {
    @BindView(R.id.video_view)
    AliyunVodPlayerView mAliyunVodPlayerView;
    @BindView(R.id.tvVideoTitle)
    TextView tvVideoTitle;
    @BindView(R.id.tvCourseName)
    TextView tvCourseName;
    @BindView(R.id.tvPeople)
    TextView tvPeople;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvFocusPeople)
    TextView tvFocusPeople;
    @BindView(R.id.tvComplete)
    TextView tvComplete;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ConsecutiveViewPager viewPager;
    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tvComment)
    TextView tvComment;
    @BindView(R.id.tvZan)
    DrawableTextView tvZan;
    @BindView(R.id.tvcollect)
    DrawableTextView tvcollect;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.llFocus)
    LinearLayout llFocus;
    @BindView(R.id.tvFocus)
    TextView tvFocus;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.rlCircle)
    RelativeLayout rlCircle;
    @BindView(R.id.progress_bar)
    ProgressBarView progress_bar;
    @BindView(R.id.tvCompleteNum)
    TextView tvCompleteNum;
    private AlivcShowMoreDialog showMoreDialog;
    private ErrorInfo currentError = ErrorInfo.Normal;
    //判断是否在后台
    private boolean mIsInBackground = false;
    private Common commenUtils;
    private long oldTime;
    private VideoEntity videoEntity;
    private MyOrderPagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private VideoDetailDirectoryFragment directoryFragment;
    private VideoDetailVideoFragment videoFragment;
    private VideoDetailCommentFragment commentFragment;
    private VideoDetailWebFragment webFragment;
    private TabPagerAdapter mAdapter;
    private List<String> titleList = new ArrayList<>();
    private String localEmployeeCode;
    private boolean isDirectoryVedio = true;//默认是目录形式的视频，个别情况是单个视频只显示评论
    private String videoPlayCounts = "0";//多少人看过视频
    private String watermark = "";//水印
    private int fansNum = 0;//多少人关注
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private long startTime = 0;
    private String authId = "";//计费所用
    private boolean isFirst = true;
    private boolean isSeek = false;
    private int index = 0;//默认展示第一个fragment
    private List<String> dialogList = new ArrayList<>();
    private BottomListsDialog bottomListsDialog = null;
    private String followStatus = "1"; //1已关注0未关注
    private int videoAllTime = 0; //当前视频时长
    private int source = 0; //0默认情况1单个视频学习任务过来的2 课程学习任务过来的
    private boolean timeEnd = false;//是否时间已到完成学习任务
    private String compeleteFlag = "";//空代表没有任务  1已经完成任务 0未完成
    private String effTime, invalidTime;//学习任务所用时间

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isStrangePhone()) {
            //            setTheme(R.style.ActTheme);
        } else {
            setTheme(R.style.NoActionTheme);
        }
        DatabaseManager.getInstance().createDataBase(this);
        setContentView(R.layout.activity_vedio_detail);
        ButterKnife.bind(this);
        startTime = System.currentTimeMillis();
    }

    @Override
    public void initData() {
        initState2();
        NavigationTools.saveUseRecord(this, "1", "14");
        localEmployeeCode = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        videoEntity = (VideoEntity) getIntent().getSerializableExtra("video");
        watermark = getIntent().getStringExtra("watermark");
        effTime = getIntent().getStringExtra("effTime");
        invalidTime = getIntent().getStringExtra("invalidTime");
        index = getIntent().getIntExtra("index", 0);
        source = getIntent().getIntExtra("source", 0);
        initAliyunPlayerView();
        requestVidSts();
        if (Utils.isNull(videoEntity.courseCode)) {
            titleList.add("评论");
            isDirectoryVedio = false;
            // 可以自定义水印文字颜色、大小和旋转角度
            if (Utils.isNull(watermark)) {
                NavigationTools.setWaterMarkFull(this, "3");
            } else {
                NavigationTools.setWaterMarkFull(this, watermark);
            }
        } else {
            isDirectoryVedio = true;
            titleList.add("视频");
            titleList.add("资料");
            titleList.add("评论");
            titleList.add("详情");
            // 可以自定义水印文字颜色、大小和旋转角度
            if (Utils.isNull(watermark)) {
                NavigationTools.setWaterMark(this, "5");
            } else {
                NavigationTools.setWaterMark(this, watermark);
            }
        }
        videoAllTime = Utils.changeNumber(videoEntity.videoSeconds);
        commentFragment = new VideoDetailCommentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("video", videoEntity);
        commentFragment.setArguments(bundle);
        if (Utils.isNull(videoEntity.courseCode)) {
            fragments.add(commentFragment);
        } else {
            directoryFragment = new VideoDetailDirectoryFragment(videoEntity.courseCode);
            videoFragment = new VideoDetailVideoFragment(videoEntity.courseCode, videoEntity.videoId, source, effTime, invalidTime);
            webFragment = new VideoDetailWebFragment(videoEntity.courseCode);
            fragments.add(videoFragment);
            fragments.add(directoryFragment);
            fragments.add(commentFragment);
            fragments.add(webFragment);
        }
        mAdapter = new TabPagerAdapter(getSupportFragmentManager(), titleList, fragments);
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setupWithViewPager(viewPager);
        if (index == 2) {
            viewPager.setCurrentItem(2);
        }
        refreshLayout.setEnableRefresh(false);
        if (!isDirectoryVedio) {
            refreshLayout.setEnableLoadMore(false);
        }
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout r) {
                if (viewPager == null) {
                    return;
                }
                if (viewPager.getCurrentItem() == 0) {
                    videoFragment.onLoadMore(refreshLayout);
                } else if (viewPager.getCurrentItem() == 1) {
                    directoryFragment.onLoadMore(refreshLayout);
                } else {
                    refreshLayout.finishLoadMore();
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout r) {
            }
        });
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                if (viewPager == null) {
                    return;
                }
                viewPager.setAdjustHeight(Utils.dip2px(VedioDetailActivity.this, 38));
            }
        });
        initUser();
        if (isDirectoryVedio) {
            getData();
        }
        startTimer();
        dialogList.add("分享");
        dialogList.add("在电脑上播放");
        dialogList.add("视频加入学习任务");
        if (!Utils.isNull(videoEntity.courseCode)) {
            dialogList.add("课程加入学习任务");
        }
        dialogList.add("取消");
        bottomListsDialog = new BottomListsDialog(this, dialogList, new SelectDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (position == 0) {
                    Intent intent = new Intent(VedioDetailActivity.this, ShareActivity.class);
                    intent.putExtra("title", videoEntity.videoTitle);
                    intent.putExtra("createEmployeeName", videoEntity.employeeName);
                    intent.putExtra("content", videoEntity.videoKeyWord);
                    intent.putExtra("resourceId", videoEntity.videoId);
                    intent.putExtra("videoShareCounts", videoEntity.videoShareCounts);
                    intent.putExtra("time", videoEntity.videoSeconds);
                    intent.putExtra("picUrl", videoEntity.videoCoverPath);
                    intent.putExtra("resourceType", 2);
                    startActivity(intent);
                } else if (position == 1) {
                    new ForScreenInitDialog(VedioDetailActivity.this, new ShareDialogListener() {
                        @Override
                        public void onClick() {
                            saveScan();
                        }
                    }).show();
                } else if (position == 2) {
                    Intent intent = new Intent(VedioDetailActivity.this, StudyPlanAddActivity.class);
                    intent.putExtra("title", videoEntity.videoTitle);
                    intent.putExtra("describe", videoEntity.videoKeyWord);
                    intent.putExtra("resourceId", videoEntity.videoId);
                    intent.putExtra("resourceType", 2);
                    intent.putExtra("time", videoEntity.videoSeconds);
                    intent.putExtra("picUrl", videoEntity.videoCoverPath);
                    startActivity(intent);
                } else if (position == 3) {
                    if (!Utils.isNull(videoEntity.courseCode)) {
                        Intent intent = new Intent(VedioDetailActivity.this, StudyPlanAddActivity.class);
                        intent.putExtra("title", tvCourseName.getText().toString());
                        intent.putExtra("describe", videoEntity.videoKeyWord);
                        intent.putExtra("resourceId", videoEntity.courseCode);
                        intent.putExtra("resourceType", 4);
                        startActivity(intent);
                    }
                }
                bottomListsDialog.dismiss();
            }
        });
    }

    /**
     * 设置屏幕亮度
     */
    private void setWindowBrightness(int brightness) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness / 255.0f;
        window.setAttributes(lp);
    }

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, 1000, 1000);//执行定时器中的任务
        }
    }

    private int allTime = 0;
    private int progressTime = 0;
    private int allVedioTime = 0;//视频总播放时长
    // handler类接收数据
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (allTime >= 0) {
                    allTime++;
                    allVedioTime++;
                    if (allTime > 1 &&allTime % MyApp.longVideoEvery == 0) {
                        addVideoCost("1");
                    }
                    if (!Utils.isNull(compeleteFlag)) {
                        if ("0".equals(compeleteFlag)) {
                            if (allTime > 1 && allTime >= videoAllTime) {
                                if (!timeEnd) {
                                    timeEnd = true;
                                    progress_bar.setVisibility(View.GONE);
                                    tvCompleteNum.setVisibility(View.VISIBLE);
                                    tvCompleteNum.setText("点击");
                                    tvComplete.setText("学习任务已完成");
                                }
                            } else {
                                tvCompleteNum.setText((videoAllTime - allTime) + "s");
                                tvComplete.setText("后完成学习");
                            }
                        }
                    }
                }
            }
        }

    };

    private void initAliyunPlayerView() {
        mAliyunVodPlayerView = (AliyunVodPlayerView) findViewById(R.id.video_view);

        //保持屏幕敞亮
        mAliyunVodPlayerView.setKeepScreenOn(true);
        mAliyunVodPlayerView.setPlayingCache(true, getExternalCacheDir().getAbsolutePath(), 60 * 60 /*时长, s */, 200 /*大小，MB*/);
        mAliyunVodPlayerView.setTheme(Theme.Red);
        mAliyunVodPlayerView.setCoverUri(videoEntity.videoCoverPath);
        mAliyunVodPlayerView.setCirclePlay(true);
        mAliyunVodPlayerView.setAutoPlay(true);
        mAliyunVodPlayerView.startNetWatch();
        mAliyunVodPlayerView.setNetConnectedListener(new MyNetConnectedListener(this));
        mAliyunVodPlayerView.setmOnPlayerViewClickListener(new MyPlayViewClickListener(this));
        mAliyunVodPlayerView.setOrientationChangeListener(new MyOrientationChangeListener(this));
        mAliyunVodPlayerView.setOnShowMoreClickListener(new MyShowMoreClickLisener(this));
        mAliyunVodPlayerView.setOnScreenBrightness(new MyOnScreenBrightnessListener(this));
        mAliyunVodPlayerView.setScreenBrightness(BrightnessDialog.getActivityBrightness(VedioDetailActivity.this));
        mAliyunVodPlayerView.setOnBack(new AliyunVodPlayerView.OnBackListener() {
            @Override
            public void onBack() {
                addPlayCount(videoEntity.videoId, allVedioTime, videoEntity.videoPlayCounts);
                finish();
            }
        });
        mAliyunVodPlayerView.setOnShare(new AliyunVodPlayerView.OnShareListener() {
            @Override
            public void onShare() {
                if (bottomListsDialog != null) {
                    bottomListsDialog.show();
                }

            }
        });
        mAliyunVodPlayerView.setOnPlayStateBtnClickListener(new AliyunVodPlayerView.OnPlayStateBtnClickListener() {
            @Override
            public void onPlayBtnClick(int playerState) {
                if (playerState == IPlayer.started) {
                   //之前为播放中 ，现在换暂停
                    allTime = -1;
                    if (!Utils.isNull(compeleteFlag)) {
                        if ("0".equals(compeleteFlag)&&!timeEnd) {
                            //任务没有完成 且 时间还未到
                            if (progress_bar != null) {
                                progress_bar.pause();
                            }
                        }
                    }
                } else if (playerState == IPlayer.paused || playerState == IPlayer.prepared || playerState == IPlayer.stopped) {
                    //之前为停止 ，现在换播放
                    if(allVedioTime % MyApp.longVideoEvery>=1){
                        allTime = allVedioTime % MyApp.longVideoEvery-1;
                    }else{
                        allTime = allVedioTime % MyApp.longVideoEvery;
                    }
                    if (!Utils.isNull(compeleteFlag)) {
                        if ("0".equals(compeleteFlag)&&!timeEnd) {
                            //任务没有完成 且 时间还未到
                            if (progress_bar != null) {
                                progress_bar.resume();
                            }
                        }
                    }
                }
            }
        });
        mAliyunVodPlayerView.setOnSeekStartListener(new AliyunVodPlayerView.OnSeekStartListener() {
            @Override
            public void onSeekStart(int position) {
                isSeek = true;
                KLog.i("-----onSeekStart");
            }
        });
        mAliyunVodPlayerView.setOnAutoPlayListener(new OnAutoPlayListener() {
            @Override
            public void onAutoPlayStarted() {
                KLog.i("-----onAutoPlayStarted");
                if (isFirst) {
                    isFirst = false;
                    allTime = 0;
                    authId = System.currentTimeMillis() + "-" + new ShareUtils().getString(VedioDetailActivity.this, StaticClass.EMPLOYEECODE, "");
                    addVideoCostTime("0", 1);
                }
            }
        });
        mAliyunVodPlayerView.setOnSeekCompleteListener(new IPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete() {
                KLog.i("-----onSeekComplete");
                if (isSeek) {
                    allTime = 0;
                    addVideoCostTime("0", 2);
                    isSeek = false;
                } else {
                    if (mAliyunVodPlayerView != null) {
                        mAliyunVodPlayerView.pause();
                        allTime = 0;
                        authId = System.currentTimeMillis() + "-" + new ShareUtils().getString(VedioDetailActivity.this, StaticClass.EMPLOYEECODE, "");
                        addVideoCostTime("0", 1);

                    }
                }
                //定时器 倒计时
//                Observable.timer(1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Consumer<Long>() {
//                            @Override
//                            public void accept(Long aLong) {
//                                try {
//                                    mAliyunVodPlayerView.pause();
//                                    KLog.i("============");
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                    mAliyunVodPlayerView.pause();
//                                }
//                            }
//                        });
            }
        });
    }

    /**
     * 请求sts
     */
    private void requestVidSts() {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", videoEntity.videoId);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.getVideoPlayAuth, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject jsonObject = reObject.getJSONObject("data");
                    compeleteFlag = jsonObject.getString("compeleteFlag");
                    allTime = 0;
                    allVedioTime = 0;
                    if (Utils.isNull(compeleteFlag)) {
                        rlCircle.setVisibility(View.GONE);
                    } else {
                        rlCircle.setVisibility(View.VISIBLE);
                        if ("1".equals(compeleteFlag)) {
                            progress_bar.setVisibility(View.GONE);
                            tvCompleteNum.setVisibility(View.GONE);
                            tvComplete.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                            tvComplete.setText("已学完");
                        } else {
                            progress_bar.setVisibility(View.VISIBLE);
                            tvCompleteNum.setVisibility(View.VISIBLE);
                            tvCompleteNum.setText((videoAllTime - allTime) + "s");
                            tvComplete.setText("后完成学习");
                            timeEnd = false;
                            progress_bar.setDuration((videoAllTime + 1) * 1000);
                            progress_bar.start();
                        }
                    }
                    VidAuth vidAuth = new VidAuth();
                    vidAuth.setVid(videoEntity.videoId);
                    vidAuth.setPlayAuth(jsonObject.getString("playAuth"));
                    isFirst = true;
                    if (mAliyunVodPlayerView != null) {
                        mAliyunVodPlayerView.setAuthInfo(vidAuth);
                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    /**
     * 增加播放时长
     */
    private void addPlayCount(String oldVideoId, long seconds, String oldVideoPlayCounts) {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", oldVideoId);
        map.put("playTime", (int) seconds + "");
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.addPlayCount, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                try {
//                    int num = Utils.changeNumber(videoPlayCounts);
                    if (tvPeople != null) {
//                        tvPeople.setText(Utils.changeCounts((num + 1) + "") + "人看过");
//                        videoEntity.videoPlayCounts = (num + 1) + "";
                        Map<String, String> eventMap = new HashMap<>();
                        eventMap.put("videoId", oldVideoId);
                        eventMap.put("videoPlayCounts", Utils.addNumber(oldVideoPlayCounts));
                        EventBus.getDefault().post(new MyEvent(eventMap));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    /**
     * 增加计费
     */
    private void addVideoCostTime(String playType, int type) {
        int time = 1;
        if (type == 1) {
            time = MyApp.startPlay;
        } else {
            time = MyApp.dragPlay;
        }
        KLog.i(MyApp.startPlay + "--" + MyApp.dragPlay);
        if (time == 0) {
            addVideoCost(playType);
        } else {
            Observable.timer(time * 1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            addVideoCost(playType);
                        }
                    });
        }

    }

    /**
     * 增加计费
     */
    private void addVideoCost(String playType) {

        Map<String, String> map = new HashMap<>();
//        （0开始播放或者拖动后 1每XX秒时扣除流量）
        map.put("videoId", videoEntity.videoId);
        map.put("playType", playType);
        map.put("authId", authId);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.getVideoCost, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {

            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    private void getData() {
//        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("videoId", videoEntity.videoId);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoDetailEntity>>() {
        }.getType(), null, Urls.selectCourseByViodeId, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoDetailEntity>() {
            @Override
            public void onSuccess(VideoDetailEntity data) {
//                dismissLoading();
                if (tvCourseName == null) {
                    return;
                }
                tvCourseName.setVisibility(View.VISIBLE);
                tvCourseName.setText(data.getCourseName());
            }

            @Override
            public void onError(String errorMsg) {
//                dismissLoading();
//                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void initUser() {
        tvVideoTitle.setText(videoEntity.videoTitle);
        videoPlayCounts = videoEntity.videoPlayCounts;
        tvPeople.setText(Utils.changeCounts(videoEntity.videoPlayCounts) + "人看过");
        tvcollect.setText(videoEntity.videoCollectCounts);
//        tvCommentNum.setText(videoEntity.videoCommentCounts);
        tvZan.setText(videoEntity.videoLikeCounts);
        GlideUtils.loadAvatar(VedioDetailActivity.this, videoEntity.headPhotoThumbUrl, ivHead);
        tvName.setText(videoEntity.employeeName);
        if ("1".equals(videoEntity.isLike)) {
            tvZan.setSelected(true);
        } else {
            tvZan.setSelected(false);
        }
        if ("1".equals(videoEntity.isCollect)) {
            tvcollect.setSelected(true);
        } else {
            tvcollect.setSelected(false);
        }

        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", videoEntity.employeeCode);
        MyHttpRequest.getRequest(Urls.getInfoByEmployeeCode, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if (Utils.isNull(jsonObject.getString("data"))) {
                            return;
                        }
                        if (llFocus == null) {
                            return;
                        }
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        if (jsonObject1.has("fansNum")) {
                            fansNum = Utils.changeNumber(jsonObject1.getString("fansNum"));
                            tvFocusPeople.setText(Utils.changeNumber(fansNum + "") + "人关注");
                            if (localEmployeeCode.equals(videoEntity.employeeCode)) {
                                llFocus.setVisibility(View.INVISIBLE);
                            } else {
                                llFocus.setVisibility(View.VISIBLE);
                                if ("1".equals(jsonObject1.getString("youIsfans"))) {
                                    followStatus = "1";
                                    llFocus.setBackgroundResource(R.drawable.shape_white_cccccc_13);
                                    tvFocus.setTextColor(Color.parseColor("#333333"));
                                    tvFocus.setText("已关注");
                                } else {
                                    followStatus = "0";
                                    llFocus.setBackgroundResource(R.drawable.shape_white_main_color_13);
                                    tvFocus.setTextColor(getResources().getColor(R.color.main_color));
                                    tvFocus.setText("+关注");
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void zanVedio() {
        Map<String, String> map = new HashMap<>();
        map.put("likeId", videoEntity.videoId);
        map.put("employeeCode", videoEntity.employeeCode);
        map.put("messageTitle", videoEntity.videoTitle);
        if (tvZan.isSelected()) {
            map.put("isLike", "-1");
        } else {
            map.put("isLike", "1");
        }
        map.put("likeType", "0");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.likeVideo, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                int num = Utils.changeNumber(tvZan.getText().toString());
                Map<String, String> eventMap = new HashMap<>();
                eventMap.put("videoId", videoEntity.videoId);
                if (tvZan == null) {
                    return;
                }
                if (tvZan.isSelected()) {
                    MyToast.show("取消点赞");
                    tvZan.setSelected(false);
                    if (num != 0) {
                        tvZan.setText((num - 1) + "");
                        videoEntity.videoLikeCounts = (num - 1) + "";
                    }
                    videoEntity.isLike = "0";

                } else {
                    MyToast.show("点赞成功");
                    tvZan.setSelected(true);
                    tvZan.setText((num + 1) + "");
                    videoEntity.isLike = "1";
                    videoEntity.videoLikeCounts = (num + 1) + "";
                }
                eventMap.put("videoLikeCounts", videoEntity.videoLikeCounts);
                eventMap.put("isLike", videoEntity.isLike);
                EventBus.getDefault().post(new MyEvent(eventMap));
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void collectVedio() {
        Map<String, String> map = new HashMap<>();
        map.put("collectId", videoEntity.videoId);
        if (tvcollect.isSelected()) {
            map.put("collectStatus", "0");
        } else {
            map.put("collectStatus", "1");
        }
        map.put("collectType", "0");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.toCollect, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                int num = Utils.changeNumber(tvcollect.getText().toString());
                Map<String, String> eventMap = new HashMap<>();
                eventMap.put("videoId", videoEntity.videoId);
                if (tvcollect == null) {
                    return;
                }
                if (tvcollect.isSelected()) {
                    MyToast.show("取消收藏");
                    tvcollect.setSelected(false);
                    if (num != 0) {
                        tvcollect.setText((num - 1) + "");
                    }
                    videoEntity.isCollect = "0";
                    videoEntity.videoCollectCounts = (num - 1) + "";
                } else {
                    MyToast.show("收藏成功");
                    tvcollect.setSelected(true);
                    tvcollect.setText((num + 1) + "");
                    videoEntity.isCollect = "1";
                    videoEntity.videoCollectCounts = (num + 1) + "";
                }
                eventMap.put("videoCollectCounts", videoEntity.videoCollectCounts);
                eventMap.put("isCollect", videoEntity.isCollect);
                EventBus.getDefault().post(new MyEvent(eventMap));
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void toFollow() {
        Map<String, String> allmap = new HashMap<>();
        if ("1".equals(followStatus)) {
            allmap.put("followStatus", "0");
        } else {
            allmap.put("followStatus", "1");
        }
        allmap.put("employeeCode", videoEntity.employeeCode);

        MyHttpRequest.getDefault().postRequestCompat(null, Urls.toFollow, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject result_object = reObject.getJSONObject("data");
                    if ("true".equals(result_object.getString("rst"))) {
                        Map<String, String> eventMap = new HashMap<>();
                        if (tvFocus == null) {
                            return;
                        }
                        if ("1".equals(followStatus)) {
                            followStatus = "0";
                            MyToast.show("取消关注");
                            llFocus.setBackgroundResource(R.drawable.shape_white_main_color_13);
                            tvFocus.setTextColor(getResources().getColor(R.color.main_color));
                            tvFocus.setText("+关注");
                            fansNum--;
                            eventMap.put("focusType", "0");
                        } else {
                            followStatus = "1";
                            MyToast.show("关注成功");
                            llFocus.setBackgroundResource(R.drawable.shape_white_cccccc_13);
                            tvFocus.setTextColor(Color.parseColor("#333333"));
                            tvFocus.setText("已关注");
                            fansNum++;
                            eventMap.put("focusType", "1");
                        }
                        eventMap.put("shapeEmployeeCode", videoEntity.employeeCode);
                        EventBus.getDefault().post(new MyEvent(eventMap));
                        tvFocusPeople.setText(Utils.changeNumber(fansNum + "") + "人关注");
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    /**
     * 完成学习任务
     */
    private void addTaskCount(String videoId) {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", videoId);
        map.put("type", "2");
        MyHttpRequest.postRequest(Urls.addTaskCount, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        videoEntity.compeleteFlag = "1";
                        compeleteFlag = "1";
                        MyToast.show("完成学习任务");
                        Map<String, String> map = new HashMap<>();
                        map.put("videoId", videoEntity.videoId);
                        map.put("compeleteFlag", "1");
                        EventBus.getDefault().post(new MyEvent(map));
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void saveScan() {
        Map<String, String> map = new HashMap<>();
        map.put("resourceId", videoEntity.videoId);
        map.put("resourceType", "2");
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.saveScan, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(errorMsg);
            }
        });
    }

    @OnClick({R.id.rlCircle, R.id.llFocus, R.id.ivHead, R.id.tvComment, R.id.tvZan, R.id.tvcollect, R.id.ivMore})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlCircle:
                if ("1".equals(compeleteFlag)) {
                    MyToast.show("您已经完成此学习任务");
                } else {
                    if (timeEnd) {
                        addTaskCount(videoEntity.videoId);
                    } else {
                        MyToast.show("还未达到学习任务规定时长");
                    }
                }
                break;
            case R.id.llFocus:
                toFollow();
                break;
            case R.id.tvComment:
                commentFragment.showReplyVideoDialog();
                break;
            case R.id.tvZan:
                zanVedio();
                break;
            case R.id.ivHead:
                Intent intent = new Intent(this, PersonalHomeActivity.class);
                intent.putExtra("employeeCode", videoEntity.employeeCode);
                startActivity(intent);
                break;
            case R.id.tvcollect:
                collectVedio();
                break;
            case R.id.ivMore:
                if (bottomListsDialog != null) {
                    bottomListsDialog.show();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(VideoEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getVideoEntity() != null) {
            addPlayCount(videoEntity.videoId, allVedioTime, videoEntity.videoPlayCounts);
            videoEntity = messageEvent.getVideoEntity();
            requestVidSts();
            commentFragment.changeData(videoEntity);
            webFragment.chageUrl(videoEntity.courseCode);
            initUser();

            videoAllTime = Utils.changeNumber(videoEntity.videoSeconds) / 10;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
//            if (tvCommentNum == null) {
//                return;
//            }
            if (map.containsKey("videoNum")) {
                tabLayout.getTabAt(0).setText("视频(" + map.get("videoNum") + ")");
            }
            if (map.containsKey("directoryNum")) {
                tabLayout.getTabAt(1).setText("资料(" + map.get("directoryNum") + ")");
            }
            if (map.containsKey("totalCommentNum")) {
                if (isDirectoryVedio) {
                    tabLayout.getTabAt(2).setText("评论(" + map.get("totalCommentNum") + ")");
                } else {
                    tabLayout.getTabAt(0).setText("评论(" + map.get("totalCommentNum") + ")");
                }
//                tvCommentNum.setText(map.get("commentNum"));
            }
        } else {
            String msg = messageEvent.getMessage();
        }
    }

    private class MyPlayViewClickListener implements AliyunVodPlayerView.OnPlayerViewClickListener {

        private WeakReference<VedioDetailActivity> weakReference;

        public MyPlayViewClickListener(VedioDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onClick(AliyunScreenMode screenMode, AliyunVodPlayerView.PlayViewType viewType) {
            long currentClickTime = System.currentTimeMillis();
            // 防止快速点击
            if (currentClickTime - oldTime <= 1000) {
                return;
            }
            oldTime = currentClickTime;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mIsInBackground = false;
        updatePlayerViewMode();
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setAutoPlay(true);
            mAliyunVodPlayerView.onResume();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mIsInBackground = true;
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setAutoPlay(false);
            mAliyunVodPlayerView.onStop();
            allTime = -1;
            if (!Utils.isNull(compeleteFlag)) {
                if ("0".equals(compeleteFlag)&&!timeEnd) {
                    //任务没有完成 且 时间还未到
                    if (progress_bar != null) {
                        progress_bar.pause();
                    }
                }
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(allVedioTime % MyApp.longVideoEvery>=1){
            allTime = allVedioTime % MyApp.longVideoEvery-1;
        }else{
            allTime = allVedioTime % MyApp.longVideoEvery;
        }
        if (!Utils.isNull(compeleteFlag)) {
            if ("0".equals(compeleteFlag)&&!timeEnd) {
                //任务没有完成 且 时间还未到
                if (progress_bar != null) {
                    progress_bar.resume();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updatePlayerViewMode();
    }

    private void updatePlayerViewMode() {
        if (mAliyunVodPlayerView != null) {
            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                //转为竖屏了。
                //显示状态栏
                //                if (!isStrangePhone()) {
                //                    getSupportActionBar().show();
                //                }
                llBottom.setVisibility(View.VISIBLE);
                line.setVisibility(View.VISIBLE);
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

                //设置view的布局，宽高之类
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = (int) (ScreenUtils.getWidth(this) * 9.0f / 16);
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //转到横屏了。
                //隐藏状态栏
                llBottom.setVisibility(View.GONE);
                line.setVisibility(View.GONE);
                if (!isStrangePhone()) {
                    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
                }
                //设置view的布局，宽高
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.onDestroy();
            mAliyunVodPlayerView = null;
        }
        if (commenUtils != null) {
            commenUtils.onDestroy();
            commenUtils = null;
        }
        stopTimer();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAliyunVodPlayerView != null) {
            boolean handler = mAliyunVodPlayerView.onKeyDown(keyCode, event);
            if (!handler) {
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //解决某些手机上锁屏之后会出现标题栏的问题。
        updatePlayerViewMode();
    }

    private static class MyOrientationChangeListener implements AliyunVodPlayerView.OnOrientationChangeListener {

        private final WeakReference<VedioDetailActivity> weakReference;

        public MyOrientationChangeListener(VedioDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void orientationChange(boolean from, AliyunScreenMode currentMode) {
            VedioDetailActivity activity = weakReference.get();

            if (activity != null) {
                activity.hideShowMoreDialog(from, currentMode);

            }
        }
    }

    /**
     * 播放器加载状态监听
     */
    private static class VideoPlayerLoadingStatusListener implements IPlayer.OnLoadingStatusListener {

        private WeakReference<VedioDetailActivity> weakReference;

        public VideoPlayerLoadingStatusListener(VedioDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onLoadingBegin() {
        }

        @Override
        public void onLoadingProgress(int percent, float v) {
            Log.i("jia", percent + "==" + v);

        }

        @Override
        public void onLoadingEnd() {

        }
    }

    private void hideShowMoreDialog(boolean from, AliyunScreenMode currentMode) {
        if (showMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                showMoreDialog.dismiss();
            }
        }
    }

    /**
     * 判断是否有网络的监听
     */
    private class MyNetConnectedListener implements AliyunVodPlayerView.NetConnectedListener {
        WeakReference<VedioDetailActivity> weakReference;

        public MyNetConnectedListener(VedioDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onReNetConnected(boolean isReconnect) {
            VedioDetailActivity activity = weakReference.get();
            if (activity != null) {
                activity.onReNetConnected(isReconnect);
            }
        }

        @Override
        public void onNetUnConnected() {
            VedioDetailActivity activity = weakReference.get();
            if (activity != null) {
                activity.onNetUnConnected();
            }
        }
    }

    private void onNetUnConnected() {
        currentError = ErrorInfo.UnConnectInternet;
    }

    private void onReNetConnected(boolean isReconnect) {
        currentError = ErrorInfo.Normal;
        if (isReconnect) {

        }
    }

    private static class MyShowMoreClickLisener implements ControlView.OnShowMoreClickListener {
        WeakReference<VedioDetailActivity> weakReference;

        MyShowMoreClickLisener(VedioDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void showMore() {
            VedioDetailActivity activity = weakReference.get();
            if (activity != null) {
                long currentClickTime = System.currentTimeMillis();
                // 防止快速点击
                if (currentClickTime - activity.oldTime <= 1000) {
                    return;
                }
                activity.oldTime = currentClickTime;
                activity.showMore(activity);
//                activity.requestVidSts();
            }

        }
    }

    private void showMore(final VedioDetailActivity activity) {
        showMoreDialog = new AlivcShowMoreDialog(activity);
        AliyunShowMoreValue moreValue = new AliyunShowMoreValue();
        moreValue.setSpeed(mAliyunVodPlayerView.getCurrentSpeed());
        moreValue.setVolume((int) mAliyunVodPlayerView.getCurrentVolume());

        ShowMoreView showMoreView = new ShowMoreView(activity, moreValue);
        showMoreDialog.setContentView(showMoreView);
        showMoreDialog.show();

        showMoreView.setOnSpeedCheckedChangedListener(new ShowMoreView.OnSpeedCheckedChangedListener() {
            @Override
            public void onSpeedChanged(RadioGroup group, int checkedId) {
                // 点击速度切换
                if (checkedId == R.id.rb_speed_normal) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.One);
                } else if (checkedId == R.id.rb_speed_onequartern) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.OneQuartern);
                } else if (checkedId == R.id.rb_speed_onehalf) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.OneHalf);
                } else if (checkedId == R.id.rb_speed_twice) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.Twice);
                }
                showMoreDialog.dismiss();
            }
        });

        /**
         * 初始化亮度
         */
        if (mAliyunVodPlayerView != null) {
            showMoreView.setBrightness(mAliyunVodPlayerView.getScreenBrightness());
        }
        // 亮度seek
        showMoreView.setOnLightSeekChangeListener(new ShowMoreView.OnLightSeekChangeListener() {
            @Override
            public void onStart(SeekBar seekBar) {

            }

            @Override
            public void onProgress(SeekBar seekBar, int progress, boolean fromUser) {
                setWindowBrightness(progress);
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setScreenBrightness(progress);
                }
            }

            @Override
            public void onStop(SeekBar seekBar) {

            }
        });

        /**
         * 初始化音量
         */
        if (mAliyunVodPlayerView != null) {
            showMoreView.setVoiceVolume(mAliyunVodPlayerView.getCurrentVolume());
        }
        showMoreView.setOnVoiceSeekChangeListener(new ShowMoreView.OnVoiceSeekChangeListener() {
            @Override
            public void onStart(SeekBar seekBar) {

            }

            @Override
            public void onProgress(SeekBar seekBar, int progress, boolean fromUser) {
                mAliyunVodPlayerView.setCurrentVolume(progress / 100.00f);
            }

            @Override
            public void onStop(SeekBar seekBar) {

            }
        });

    }

    private static class MyOnScreenBrightnessListener implements AliyunVodPlayerView.OnScreenBrightnessListener {

        private WeakReference<VedioDetailActivity> weakReference;

        public MyOnScreenBrightnessListener(VedioDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onScreenBrightness(int brightness) {
            VedioDetailActivity aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.setWindowBrightness(brightness);
                if (aliyunPlayerSkinActivity.mAliyunVodPlayerView != null) {
                    aliyunPlayerSkinActivity.mAliyunVodPlayerView.setScreenBrightness(brightness);
                }
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event != null && event.getKeyCode() == 67) {
            if (mAliyunVodPlayerView != null) {
                //删除按键监听,部分手机在EditText没有内容时,点击删除按钮会隐藏软键盘
                return false;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    protected boolean isStrangePhone() {
        boolean strangePhone = false;
        try {
            strangePhone = "mx5".equalsIgnoreCase(Build.DEVICE)
                    || "Redmi Note2".equalsIgnoreCase(Build.DEVICE)
                    || "Z00A_1".equalsIgnoreCase(Build.DEVICE)
                    || "hwH60-L02".equalsIgnoreCase(Build.DEVICE)
                    || "hermes".equalsIgnoreCase(Build.DEVICE)
                    || ("V4".equalsIgnoreCase(Build.DEVICE) && "Meitu".equalsIgnoreCase(Build.MANUFACTURER))
                    || ("m1metal".equalsIgnoreCase(Build.DEVICE) && "Meizu".equalsIgnoreCase(Build.MANUFACTURER));

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return strangePhone;
    }

    /**
     * 停止定时器，初始化定时器开关
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    @Override
    public void onBackPressed() {
        addPlayCount(videoEntity.videoId, allVedioTime, videoEntity.videoPlayCounts);
        super.onBackPressed();
    }
}
